import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:village_android/model/article_model.dart';
import 'package:village_android/pages/browser.dart';

class CustomBanner extends StatefulWidget {
  List _images;
  final double height;
  final ValueChanged<int> onTap;
  final Curve curve;

  CustomBanner(
    this._images, {
    this.height = 170,
    this.onTap,
    this.curve = Curves.linear,
  }) : assert(_images != null);

  @override
  _CustomBannerState createState() => _CustomBannerState();
}

class _CustomBannerState extends State<CustomBanner> {
  PageController _pageController;
  int _curIndex;
  Timer _timer;

  @override
  void initState() {
    super.initState();
    _curIndex = widget._images.length * 5;
    _pageController = PageController(initialPage: _curIndex);
    _initTimer();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.bottomCenter,
      children: <Widget>[
        _buildPageView(),
        _buildIndicator(),
      ],
    );
  }

  Widget _buildIndicator() {
    var length = widget._images.length;
    return Positioned(
      bottom: 10,
      child: Row(
        children: widget._images.map((s) {
          return Padding(
            padding: const EdgeInsets.symmetric(horizontal: 3.0),
            child: ClipOval(
              child: Container(
                width: 4,
                height: 4,
                color: s == widget._images[_curIndex % length]
                    ? Colors.white
                    : Colors.grey,
              ),
            ),
          );
        }).toList(),
      ),
    );
  }

  Widget _buildPageView() {
    var length = widget._images.length;
    if(length==0){
      return Container(
        height: widget.height,
        child: SizedBox(height: widget.height,),
      );
    }
    return Container(
      height: widget.height,
      child: PageView.builder(
        controller: _pageController,
        onPageChanged: (index) {
          setState(() {
            _curIndex = index;
            if (index == 0) {
              _curIndex = length;
              _changePage();
            }
          });
        },
        itemBuilder: (context, index) {
          return GestureDetector(
            onPanDown: (details) {
              _cancelTimer();
            },
            onTap: () {
              ArticleModel item = new ArticleModel();
              item.title = widget._images[index % length]["title"];
              item.url = widget._images[index % length]["url"];
              onItemClick(item);
//              Scaffold.of(context).showSnackBar(
//                SnackBar(
//                  content: Text('当前 page 为 ${index % length}'),
//                  duration: Duration(milliseconds: 500),
//                ),
//              );
            },
            child: Stack(
              fit: StackFit.expand,
              children: <Widget>[
                Container(
                  child: Image.network(
                    widget._images[index % length]["coverUrl"],
                    height: 250,
                    width: double.infinity,
                    fit: BoxFit.cover,
                  ),
                ),
                Positioned(
                    bottom: 0,
                    child:
                        initTitleLabel(widget._images[index % length]["title"])
//                  Container(
//                    alignment: Alignment.center,
//                    child: FittedBox(
//                      fit: BoxFit.contain,
//                      child: Text(
//                        widget._images[index % length]["title"],
//                        style: TextStyle(
//                            fontSize: 14.0,
//                            color: Colors.white,
//                            backgroundColor: Color.fromRGBO(0, 0, 0, 0.5)),
//                      ),
//                    ),
//                  ),
                    ),
              ],
            ),
          );
        },
      ),
    );
  }

  Align initTitleLabel(title) {
    return Align(
        alignment: Alignment.center,
        child: Column(children: <Widget>[
          SizedBox(
            height: 40.0,
            width: MediaQuery.of(context).size.width,
            child: Container(
              child: Padding(
                  padding: const EdgeInsets.all(10.0),
                  child: Text(
                    title,
                    textAlign: TextAlign.left,
                    style: TextStyle(color: Colors.white,fontSize: 15),
                  )),
              color: Color.fromRGBO(0, 0, 0, 0.4),
            ),
          ),
        ]));
  }

  void onItemClick(item) {
//    item = ArticleModel.fromJson(item);
    var page = new BrowserPage(
      title: item.title,
      url: item.url,
    );
    Navigator.push(context, new MaterialPageRoute(builder: (context) => page));
  }

  /// 点击到图片的时候取消定时任务
  _cancelTimer() {
    if (_timer != null) {
      _timer.cancel();
      _timer = null;
      _initTimer();
    }
  }

  /// 初始化定时任务
  _initTimer() {
    if (_timer == null) {
      _timer = Timer.periodic(Duration(seconds: 3), (t) {
        _curIndex++;
        _pageController.animateToPage(
          _curIndex,
          duration: Duration(milliseconds: 300),
          curve: Curves.linear,
        );
      });
    }
  }

  /// 切换页面，并刷新小圆点
  _changePage() {
    Timer(Duration(milliseconds: 350), () {
      _pageController.jumpToPage(_curIndex);
    });
  }
}
